/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

import { ListNode } from '../../helper/ListNode'

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
export var addTwoNumbers = function (l1, l2) {
  let [cur1, cur2, cur, carry] = [l1, l2, null, 0]
  let ans = null
  while (cur1 || cur2) {
    const [val1, val2] = [cur1?.val || 0, cur2?.val || 0]
    const sum = val1 + val2 + carry
    if (!ans) {
      ans = new ListNode()
      cur = ans
    }
    carry = sum >= 10 ? 1 : 0
    cur.val = sum % 10
    ;[cur1, cur2] = [cur1 ? cur1.next : null, cur2 ? cur2.next : null]
    if (cur1 || cur2) {
      cur.next = new ListNode()
      cur = cur.next
    }
  }
  if (carry) {
    cur.next = new ListNode(1)
  }
  return ans
}
